<script>
	var RUB = 0.0;
	var jsonRates = null;
	var pathname = '';
	var tempCode, tempPrice;
	var isClicked = false;
	var selectedCode;

	$(document).ready(function () {
		
		// Focus autocomplete currency input when click currency on the topbar
		$('#a-currencyTopBar').click(function (){
			$('#autocompleteCurrency').val('');
			$('#autocompleteCurrency').focus();
		});
	    		
		pathname = window.location.pathname;
	    
    	var exchangeRates = '${sessionScope.exchangeRates}';
    	if(exchangeRates === ''){
		    $.ajax({
				url : "${pageContext.request.contextPath}/latest_exchange_rates.html",
				type : 'GET',
				dataType : "text",
				beforeSend : function(xhr) {
					xhr.setRequestHeader("Accept", "application/json");
					xhr.setRequestHeader("Content-Type", "application/json");
				},
				success : function(string) {
					jsonRates = $.parseJSON(string);
					getJsonFromController();
				},
				error : function(string) {
					
				}
		    });
    	}else{
    		jsonRates =  $.parseJSON(exchangeRates);
			getJsonFromController();
    	}

		// Just do in after exchange rates
        if(pathname.indexOf("exchange_rates/code") != -1){
        	selectedCode = pathname.substring(pathname.length - 8, pathname.length - 5);
			$('#currencyTopBar').empty().append(selectedCode);
        }
	});

	// Change price when load page
	function changePriceList() {
		// Get Current Currency Code on topbar
		var code = $('#currencyTopBar').html();
		selectedCode = code.trim();

		changePrice(selectedCode);
	}

	// Change price when click on the dropdown topbar
	function changePriceDropDownBt(currencyCodeDropDown){

		var stringItem = currencyCodeDropDown.textContent;
		var arrayStringtemp = new Array();

		arrayStringtemp = stringItem.split("-");
		selectedCode = arrayStringtemp[0].trim();
		
		// Just do in create task page
        if(pathname.indexOf("task/create") != -1 || pathname.indexOf("task/edit") != -1){
        	isClicked = true;
        	tempCode = $(".postfix").html();
        	$(".postfix").empty().append(selectedCode);
        	$("#currency").val(selectedCode);
        }
		var currencyTopBar = document.getElementById("currencyTopBar");
		currencyTopBar.innerHTML = selectedCode;

		// Just do in exchange rates page
        if(pathname.indexOf("exchange_rates") != -1){
        	showLoading();
        	window.location.href = "${pageContext.request.contextPath}/exchange_rates/code/" + selectedCode + ".html";
        	document.getElementsById("currencyTopBar").innerHTML = selectedCode;
        }else{
			changePrice(selectedCode);
        }
	}
	
	function changePriceNotification(){
		//notification topbar
		var priceNotification =  document.getElementsByName("priceNotification");
		var inputHiddenNotification = document.getElementsByName("inputHiddenNotification");
		var codeCurrencyNotification =  document.getElementsByName("codeCurrencyNotification");
		
		var code = $('#currencyTopBar').html();
		selectedCode = code.trim(); 
		

    	$.each(jsonRates, function (idx, obj) {
    		if (selectedCode == obj.code) {
				selectedRate = obj.rate;
			}
    	});
		
		for (var i = 0; i < priceNotification.length; i++) {
			var val = inputHiddenNotification[i].value;
			var tam = parseFloat(val);
			var kq = tam * (selectedRate / RUB);
			priceNotification[i].innerHTML = addCommas(kq.toFixed(2));
			codeCurrencyNotification[i].innerHTML = selectedCode;
		}
	}

	function changePrice(selectedCode){
		
		var selectedRate = 0.0;
		if(jsonRates != null){
			$.each(jsonRates, function (idx, obj) {
	    		if (selectedCode == obj.code) {
					selectedRate = obj.rate;
				}
	    	});
		}
		// Just do in create task page
        if(pathname.indexOf("task/create") != -1 || pathname.indexOf("task/edit") != -1){
        	if(isClicked == true){
	        	var tempRate = 0.0;
	
	        	$.each(jsonRates, function (idx, obj) {
	        		if (tempCode == obj.code) {
	        			tempRate = obj.rate;
	    			}
	        	});
	        	
	        	tempPrice = $("#maxPrice").val();
	        	var newPrice = tempPrice * (selectedRate / tempRate);
	        	$("#maxPrice").val(newPrice.toFixed(2));
        	}
        }else{
			var vrows = document.getElementsByName("vrow");
			var realValues = document.getElementsByName("realValue");
			var vrowCodes = document.getElementsByName("vrowCode");
			
			for (var i = 0; i < vrows.length; i++) {
				var val = realValues[i].value;
				var tam = parseFloat(val);
				var kq = tam * (selectedRate / RUB);

				vrows[i].innerHTML = addCommas(kq.toFixed(2));
				vrowCodes[i].innerHTML = selectedCode;
			}
        }

		//notification topbar
		var priceNotification =  document.getElementsByName("priceNotification");
		var inputHiddenNotification = document.getElementsByName("inputHiddenNotification");
		var codeCurrencyNotification =  document.getElementsByName("codeCurrencyNotification");
		
		for (var i = 0; i < priceNotification.length; i++) {
			var val = inputHiddenNotification[i].value;
			var tam = parseFloat(val);
			var kq = tam * (selectedRate / RUB);
			priceNotification[i].innerHTML = addCommas(kq.toFixed(2));
			codeCurrencyNotification[i].innerHTML = selectedCode;
		}
	}

	function addCommas(n) {
		var rx = /(\d+)(\d{3})/;
		return String(n).replace(/^\d+/, function(w) {
			while (rx.test(w)) {
				w = w.replace(rx, '$1,$2');
			}
			return w;
		});
	}
	
	function getJsonFromController(){
		// sort currency list by code
		jsonRates = jsonRates.sort(function (a, b) {
			if (a.code < b.code) return -1;
			if (b.code < a.code) return 1;
         	return 0;
         });
		
		// show currency list on top bar
		var list = [];
		$.each(jsonRates, function (idx, obj) {
			var code_name = obj.code + ' - ' + obj.name; 
			var jsonObj = { value: obj.code, label: code_name };
			list.push(jsonObj);
			if(obj.code == 'RUB'){
				RUB = obj.rate;
			}
			//$("#drop2").append('<li class="editLiTopBar"><a onclick="changePriceDropDownBt(this)" class="colorOfLi">' + obj.code + ' - ' + obj.name + '</a></li>');
     	});

		var inputCurrency = $("#autocompleteCurrency"); 
		$(function() {
			inputCurrency.autocomplete({
				source : list,
				autoFocus: true,
				focus : function(event, ui) {
					// prevent autocomplete from updating the textbox
					event.preventDefault();
					// manually update the textbox
					// $(this).val(ui.item.label);
				},
				select : function(event, ui) {
					// prevent autocomplete from updating the textbox
					event.preventDefault();
					// manually update the textbox and hidden field
					$(this).val(ui.item.label);
					var currencyTopBar = document.getElementById("currencyTopBar");
					currencyTopBar.innerHTML = ui.item.value;
					$("#autocompleteCurrency").val('');
					updateCurrencyCode(ui.item.value);
				}
			}).autocomplete("widget").addClass("fixPanelMenuCurrency");
		});
		
		var wasOpen = false;
		$('#div-showallcurrencies').append($("<a>")
            .attr( "tabIndex", -1 )
            .attr( "title", "Show All Currencies" )
            .tooltip()
            .button({
              icons: {
                primary: "ui-icon-triangle-1-s"
              },
              text: false
            })
            .removeClass( "ui-corner-all" )
            .addClass( "custom-combobox-toggle ui-corner-right ui-icon-triangle-1-s showAllCurrencies" )
            .mousedown(function() {
            	wasOpen = inputCurrency.autocomplete( "widget" ).is( ":visible" );
            })
            .click(function() {
            	inputCurrency.focus();
	 
	            // Close if already visible
	            if ( wasOpen ) {
	              return;
	            }
	 
	            // Pass empty string as value to search for, displaying all results
	            inputCurrency.autocomplete("search", " ");
	         }));

		// Show all currencies when double click in input
		$("#autocompleteCurrency").dblclick(function() {
            inputCurrency.autocomplete("search", " ");
		});
		changePriceList();
	}

	$(window).bind(
			"load",
			function() {
				// Just do in profile page
				if (pathname.indexOf("profile") != -1) {
					var currency_code = '${sessionScope.currency_code}';
					var selected = '';
					if (currency_code === '') {
						selected = 'selected';
					} else {
						selected = '';
					}
					$.each(jsonRates, function(idx, obj) {
						if (obj.code === currency_code) {
							selected = 'selected';
						} else {
							selected = '';
						}
						$("#currency-list").append(
								'<option value =" '+ obj.code + '"' + selected + '>'
										+ obj.code + ' - ' + obj.name
										+ '</option>');
					});
				}
			});
</script>